<template>
  <div class="file-upload-container">
    <h2>文件上传</h2>

    <div class="upload-area" @click="triggerFileInput" @dragover.prevent @drop="handleDrop">
      <input
        type="file"
        ref="fileInput"
        @change="handleFileChange"
        style="display: none;"
        :multiple="multiple"
      >
      <div v-if="!selectedFile" class="upload-prompt">
        <i class="el-icon-upload"></i>
        <p>点击或拖拽文件到此处上传</p>
      </div>
      <div v-else class="file-info">
        <p><i class="el-icon-document"></i> {{ selectedFile.name }}</p>
        <p>大小: {{ formatFileSize(selectedFile.size) }}</p>
      </div>
    </div>

    <div class="upload-controls">
      <el-button
        type="primary"
        @click="startUpload"
        :disabled="!selectedFile || uploading"
      >
        {{ uploading ? '上传中...' : '开始上传' }}
      </el-button>
      <el-button @click="clearSelection" :disabled="!selectedFile || uploading">
        取消选择
      </el-button>
    </div>

    <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-container">
      <el-progress
        :percentage="uploadProgress"
        :status="uploadStatus"
        :stroke-width="12"
      ></el-progress>
      <p>{{ uploadProgress }}%</p>
    </div>

    <div v-if="uploadResult" class="result-message" :class="uploadResult.success ? 'success' : 'error'">
      <i :class="uploadResult.success ? 'el-icon-success' : 'el-icon-error'"></i>
      <span>{{ uploadResult.message }}</span>
      <p v-if="uploadResult.data">文件路径: {{ uploadResult.data.filePath }}</p>
    </div>

    <div class="upload-options">
      <el-button @click="downloadStaticExcel()" >下载模版</el-button>
    </div>
  </div>
</template>

<script>
import * as Util from "@/utils";
export default {
  name: 'FileUpload',
  data() {
    return {
      selectedFile: null,
      uploading: false,
      uploadProgress: 0,
      uploadStatus: '',
      uploadResult: null,
      multiple: false,
      overwrite: false
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    handleFileChange(event) {
      const files = event.target.files
      if (files && files.length > 0) {
        this.selectedFile = this.multiple ? files : files[0]
        this.uploadResult = null
      }
    },
    handleDrop(event) {
      event.preventDefault()
      const files = event.dataTransfer.files
      if (files && files.length > 0) {
        this.selectedFile = this.multiple ? files : files[0]
        this.uploadResult = null
      }
    },
    clearSelection() {
      this.selectedFile = null
      this.uploadProgress = 0
      this.uploadResult = null
      this.$refs.fileInput.value = ''
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    async startUpload() {
      if (!this.selectedFile) return

      this.uploading = true
      this.uploadProgress = 0
      this.uploadStatus = ''
      this.uploadResult = null

      try {
        const formData = new FormData()

        if (this.multiple) {
          Array.from(this.selectedFile).forEach(file => {
            formData.append('files', file)
          })
        } else {
          formData.append('file', this.selectedFile)
        }

        // 添加额外参数
        formData.append('overwrite', this.overwrite)
        formData.append('customer_id', this.$util.cookies.get('customer_id'))
        //formData.append('uploader', this.$store.state.user.name || 'anonymous')

        const response = this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/file/import-excel'),
          method: 'post',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            if (progressEvent.lengthComputable) {
              this.uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            }
          }
        })
        //alert(JSON.stringify(response))
        this.uploadStatus = 'success'
        this.uploadResult = {
          success: true,
          message: '文件上传成功',
          data: response.data
        }
      } catch (error) {
        console.error('上传失败:', error)
        this.uploadStatus = 'exception'
        this.uploadResult = {
          success: false,
          message: error.response?.data?.message || '文件上传失败'
        }
      } finally {
        this.uploading = false
        if (this.uploadProgress < 100) {
          this.uploadProgress = 100
        }
      }
    },
    downloadStaticExcel() {
          const link = document.createElement('a')
          link.href = '/ecs/file/download/report.xlsx' // 服务器上的文件路径
          link.download = 'report.xlsx' // 下载后的文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
  }
}
</script>

<style scoped>
.file-upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #409EFF;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
  margin-bottom: 20px;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-prompt {
  color: #909399;
}

.upload-prompt i {
  font-size: 40px;
  margin-bottom: 10px;
  color: #C0C4CC;
}

.file-info {
  color: #606266;
}

.file-info i {
  margin-right: 8px;
  color: #409EFF;
}

.upload-controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 20px;
}

.progress-container {
  margin: 20px 0;
  text-align: center;
}

.result-message {
  padding: 15px;
  border-radius: 4px;
  margin: 20px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-message i {
  font-size: 20px;
  margin-right: 10px;
}

.result-message.success {
  background-color: #f0f9eb;
  color: #67C23A;
}

.result-message.error {
  background-color: #fef0f0;
  color: #F56C6C;
}

.upload-options {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}
</style>
